import datetime
now = datetime.datetime.now()
print ("Última versión:")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
import pandas as pd
import numpy as np
import pandas_profiling
from itertools import combinations
from dateutil.parser import parse
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import seaborn as sns
import plotly.express as px
#parámetros de las gráficas 3d
elev = 50.0
azim = 120.0
#datos procesados
datos = pd.read_csv("C:/Users/miguel.alvarez/Google Drive/INFOTEC/Proyecto/Code-Data/Secc/1_Procesamiento/Resultados_Datos-procesados_secc2019.csv", encoding='utf-8')
print(datos.dtypes)
datos
#se reordena y eliminan del dataframe las variables que no se usarán
datos_secc = datos.drop(columns=['Coef_Var_PE', 'Var_Prop_PE', 'Autocorr_PE','Area_Km2'])
datos_secc = datos_secc.reindex(columns= ['EDO','NOMBRE_ESTADO','MUN','NOMBRE_MUNICIPIO','DTO','SECC','TIPO_SECCION','LNE','Densidad_LNE','Razon_LNE_PE','TC_LNE_2019','Coef_Var_LNE','Var_Prop_LNE','Autocorr_LNE'])
#verificar si hay valores nulos en datos_secc
datos_secc.isnull().sum()
#se eliminan las filas (secciones) con valores vacíos
datos_secc_limpio = datos_secc.dropna()
datos_secc_limpio = datos_secc_limpio.reset_index(drop=True) #para reordenar el índice del nuevo dataframe
datos_secc_limpio.isnull().sum()
#se separan los indicadores de los metadatos
#metadatos
metadatos = datos_secc_limpio[['EDO', 'NOMBRE_ESTADO', 'MUN', 'NOMBRE_MUNICIPIO', 'DTO','SECC','TIPO_SECCION']]
metadatos.head()
#indicadores (features)
datos_secc_limpio_f = datos_secc_limpio[['LNE', 'Densidad_LNE', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Var_Prop_LNE','Autocorr_LNE']]
datos_secc_limpio_f
#resumen estadístico
datos_secc_limpio_f.describe()
#histogramas de los indicadores base
#print(sum(datos_secc['LNE'] > 500000))
plt.figure(figsize=(20,10))
plt.subplot(242)
H = plt.hist(datos_secc_limpio_f['LNE'], bins = 100)
plt.subplot(243)
H = plt.hist(datos_secc_limpio_f['Densidad_LNE'], bins = 100)
plt.subplot(244)
H = plt.hist(datos_secc_limpio_f['Razon_LNE_PE'], bins = 100)
plt.subplot(245)
H = plt.hist(datos_secc_limpio_f['TC_LNE_2019'], bins = 100)
plt.subplot(246)
H = plt.hist(datos_secc_limpio_f['Coef_Var_LNE'], bins = 100)
plt.subplot(247)
H = plt.hist(datos_secc_limpio_f['Var_Prop_LNE'], bins = 100)
plt.subplot(248)
H = plt.hist(datos_secc_limpio_f['Autocorr_LNE'], bins = 100)
#Plot correlogram
#(see https://www.machinelearningplus.com/plots/top-50-matplotlib-visualizations-the-master-plots-python/)
plt.figure(figsize=(10,6), dpi= 200)
sns.heatmap(datos_secc_limpio_f.corr(), xticklabels=datos_secc_limpio_f.corr().columns, yticklabels=datos_secc_limpio_f.corr().columns, cmap='RdYlGn', center=0, annot=True)
# fix for mpl bug that cuts off top/bottom of seaborn viz (see https://github.com/mwaskom/seaborn/issues/1773)
b, t = plt.ylim() # discover the values for bottom and top
b += 0.5 # Add 0.5 to the bottom
t -= 0.5 # Subtract 0.5 from the top
plt.ylim(b, t) # update the ylim(bottom, top) values
plt.title('Correlaciones (7 indicadores base)')
#se guarda la grafica
plt.savefig('Pyplot_heatmap_ind7.png',dpi=600, bbox_inches="tight")
plt.show()
#pair-plot
#(see https://www.machinelearningplus.com/plots/top-50-matplotlib-visualizations-the-master-plots-python/)
corr1 = sns.pairplot(datos_secc_limpio_f)
corr1.fig.suptitle("Correlograma (7 indicadores base)", y=1.01)
corr1.savefig('Pyplot_correlogram_ind7.png',dpi=600)
datos_secc_limpio_f_ind6 = datos_secc_limpio_f[['LNE', 'Densidad_LNE', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE','Autocorr_LNE']]
#Plot correlogram
#(see https://www.machinelearningplus.com/plots/top-50-matplotlib-visualizations-the-master-plots-python/)
plt.figure(figsize=(10,6), dpi= 200)
sns.heatmap(datos_secc_limpio_f_ind6.corr(), xticklabels=datos_secc_limpio_f_ind6.corr().columns, yticklabels=datos_secc_limpio_f_ind6.corr().columns, cmap='RdYlGn', center=0, annot=True)
# fix for mpl bug that cuts off top/bottom of seaborn viz (see https://github.com/mwaskom/seaborn/issues/1773)
b, t = plt.ylim() # discover the values for bottom and top
b += 0.5 # Add 0.5 to the bottom
t -= 0.5 # Subtract 0.5 from the top
plt.ylim(b, t) # update the ylim(bottom, top) values
plt.title('Correlaciones (6 indicadores base)')
#se guarda la grafica
plt.savefig('Pyplot_heatmap_ind6.png',dpi=600,bbox_inches="tight")
plt.show()
#pair-plot
#(see https://www.machinelearningplus.com/plots/top-50-matplotlib-visualizations-the-master-plots-python/)
corr2_tf = sns.pairplot(datos_secc_limpio_f_ind6)
corr2_tf.fig.suptitle("Correlograma (6 indicadores base)", y=1.01)
corr2_tf.savefig('Pyplot_correlogram_ind6.png',dpi=600)
#se transforman algunos indicadores para analizar escenarios
datos_secc_limpio_f_tf = datos_secc_limpio_f.copy()
#np-log de LNE, Densidad
datos_secc_limpio_f_tf['LNE'] = np.log(datos_secc_limpio_f_tf['LNE'])
datos_secc_limpio_f_tf['Densidad_LNE'] = np.log(datos_secc_limpio_f_tf['Densidad_LNE'])
#datos_secc_limpio_f_tf['NUM_SECC_RUR'] = np.log(datos_secc_limpio_f_tf['NUM_SECC_RUR']+1)
#renombramos algunas columnas
datos_secc_limpio_f_tf=datos_secc_limpio_f_tf.rename(columns={"LNE": "log(LNE)", "Densidad_LNE": "log(Densidad_LNE)"})
#resumen estadístico
datos_secc_limpio_f_tf.describe()
#histogramas de los indicadores base
#print(sum(datos_secc['log(LNE')] > 500000))
plt.figure(figsize=(20,10))
plt.subplot(242)
H = plt.hist(datos_secc_limpio_f_tf['log(LNE)'], bins = 100)
plt.subplot(243)
H = plt.hist(datos_secc_limpio_f_tf['log(Densidad_LNE)'], bins = 100)
plt.subplot(244)
H = plt.hist(datos_secc_limpio_f_tf['Razon_LNE_PE'], bins = 100)
plt.subplot(245)
H = plt.hist(datos_secc_limpio_f_tf['TC_LNE_2019'], bins = 100)
plt.subplot(246)
H = plt.hist(datos_secc_limpio_f_tf['Coef_Var_LNE'], bins = 100)
plt.subplot(247)
H = plt.hist(datos_secc_limpio_f_tf['Var_Prop_LNE'], bins = 100)
plt.subplot(248)
H = plt.hist(datos_secc_limpio_f_tf['Autocorr_LNE'], bins = 100)
#Plot correlogram
#(see https://www.machinelearningplus.com/plots/top-50-matplotlib-visualizations-the-master-plots-python/)
plt.figure(figsize=(10,6), dpi= 200)
sns.heatmap(datos_secc_limpio_f_tf.corr(), xticklabels=datos_secc_limpio_f_tf.corr().columns, yticklabels=datos_secc_limpio_f_tf.corr().columns, cmap='RdYlGn', center=0, annot=True)
# fix for mpl bug that cuts off top/bottom of seaborn viz (see https://github.com/mwaskom/seaborn/issues/1773)
b, t = plt.ylim() # discover the values for bottom and top
b += 0.5 # Add 0.5 to the bottom
t -= 0.5 # Subtract 0.5 from the top
plt.ylim(b, t) # update the ylim(bottom, top) values
plt.title('Correlaciones (7 indicadores base, con transformación log en LNE y Densidad_LNE)')
#se guarda la grafica
plt.savefig('Pyplot_heatmap_ind7_tf.png',dpi=600,bbox_inches="tight")
plt.show()
#pair-plot
#(see https://www.machinelearningplus.com/plots/top-50-matplotlib-visualizations-the-master-plots-python/)
corr1_tf = sns.pairplot(datos_secc_limpio_f_tf)
corr1_tf.fig.suptitle("Correlograma (7 indicadores base, con transformación log en LNE y Densidad_LNE)", y=1.01)
corr1_tf.savefig('Pyplot_correlogram_ind7_tf.png',dpi=600)
datos_secc_limpio_f_tf_ind6 = datos_secc_limpio_f_tf[['log(LNE)', 'log(Densidad_LNE)', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE','Autocorr_LNE']]
#Plot correlogram
#(see https://www.machinelearningplus.com/plots/top-50-matplotlib-visualizations-the-master-plots-python/)
plt.figure(figsize=(10,6), dpi= 200)
sns.heatmap(datos_secc_limpio_f_tf_ind6.corr(), xticklabels=datos_secc_limpio_f_tf_ind6.corr().columns, yticklabels=datos_secc_limpio_f_tf_ind6.corr().columns, cmap='RdYlGn', center=0, annot=True)
# fix for mpl bug that cuts off top/bottom of seaborn viz (see https://github.com/mwaskom/seaborn/issues/1773)
b, t = plt.ylim() # discover the values for bottom and top
b += 0.5 # Add 0.5 to the bottom
t -= 0.5 # Subtract 0.5 from the top
plt.ylim(b, t) # update the ylim(bottom, top) values
plt.title('Correlaciones (6 indicadores base, con transformación log en LNE y Densidad_LNE)')
#se guarda la grafica
plt.savefig('Pyplot_heatmap_ind6_tf.png',dpi=600,bbox_inches="tight")
plt.show()
#pair-plot
#(see https://www.machinelearningplus.com/plots/top-50-matplotlib-visualizations-the-master-plots-python/)
corr2_tf = sns.pairplot(datos_secc_limpio_f_tf_ind6)
corr2_tf.fig.suptitle("Correlograma (6 indicadores base, con transformación log en LNE y Densidad_LNE)", y=1.01)
corr2_tf.savefig('Pyplot_correlogram_ind6_tf.png',dpi=600)
from sklearn.preprocessing import StandardScaler
#Se crean listas para separar los tipos/escenarios de datos
#seleccionamos 6 indicadores
ind6 = ['LNE', 'Densidad_LNE', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Autocorr_LNE']
#seleccionamos 6 indicadores (con log)
ind6_tf = ['log(LNE)', 'log(Densidad_LNE)', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Autocorr_LNE']
#seleccionamos 7 indicadores
ind7 = ['LNE', 'Densidad_LNE', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Var_Prop_LNE', 'Autocorr_LNE']
#seleccionamos 7 indicadores (con log)
ind7_tf = ['log(LNE)', 'log(Densidad_LNE)', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Var_Prop_LNE', 'Autocorr_LNE']
#etiquetas
labels = ['EDO', 'NOMBRE_ESTADO', 'MUN', 'NOMBRE_MUNICIPIO', 'DTO','SECC','TIPO_SECCION']
#seleccionamos los valores de solo 6 indicadores (sin Var_Prop_LNE)
x = datos_secc_limpio_f.loc[:, ind6].values
#seleccionamos los valores de solo 6 indicadores (sin Var_Prop_LNE y con log)
x_1 = datos_secc_limpio_f_tf.loc[:, ind6_tf].values
#seleccionamos los valores de los 7 indicadores originales
x_2 = datos_secc_limpio_f.loc[:, ind7].values
#seleccionamos los valores de los 7 indicadores con transformacion log en LNE y Densidad
x_3 = datos_secc_limpio_f_tf.loc[:, ind7_tf].values
#seleccionamos las labels (metadatos)
y = metadatos.loc[:,labels].values
print(x.shape)
print(x_1.shape)
print(x_2.shape)
print(x_3.shape)
print(y.shape)
#para verificar que no haya valores nulos o infinitos en ind6
print(np.any(np.isnan(x)))
print(np.all(np.isfinite(x)))
#para verificar que no haya valores nulos o infinitos en ind6_tf
print(np.any(np.isnan(x_1)))
print(np.all(np.isfinite(x_1)))
#para verificar que no haya valores nulos o infinitos en ind7
print(np.any(np.isnan(x_2)))
print(np.all(np.isfinite(x_2)))
#para verificar que no haya valores nulos o infinitos en ind7_tf
print(np.any(np.isnan(x_3)))
print(np.all(np.isfinite(x_3)))
#Estandarizamos los valores de ind6 (normalización)
x = StandardScaler().fit_transform(x)
print(x.shape)
#Estandarizamos los valores de ind6_tf (normalización)
x_1 = StandardScaler().fit_transform(x_1)
print(x_1.shape)
#Estandarizamos los valores de ind7 (normalización)
x_2 = StandardScaler().fit_transform(x_2)
print(x_2.shape)
#Estandarizamos los valores de ind7_tf (normalización)
x_3 = StandardScaler().fit_transform(x_3)
print(x_3.shape)
from sklearn.decomposition import PCA
#calculo de PCA (con las 6 componentes), y obtención de los valores CP para cada sección
pca_6cp = PCA(n_components=6)
pca_ind6 = pca_6cp.fit_transform(x)
#razones de varianza explicada por cada CP
print('Razón de varianza explicada por cada CP (n_components=6): %s'
% str(pca_6cp.explained_variance_ratio_))
#dataframe con los valores de los 6 CP por sección
df_pca_ind6 = pd.DataFrame(data = pca_ind6
, columns = ['CP1', 'CP2', 'CP3','CP4', 'CP5', 'CP6'])
df_pca_ind6
#obtención de los pesos por cada variable
pca_pesos_ind6 = pca_6cp.components_
print(pca_pesos_ind6)
#transformación a un dataframe:
df_pca_pesos_ind6 = pd.DataFrame(pca_pesos_ind6, columns=ind6)
principal_components_pesos = pd.DataFrame(['CP1', 'CP2', 'CP3','CP4', 'CP5', 'CP6'])
df_pca_pesos_ind6.insert(0, 'Componentes Principales', principal_components_pesos)
#se guarda el último dataframe en un csv
df_pca_pesos_ind6.to_csv(r'Resultados_Secc_PCA_pesos_ind6.csv', index = None)
df_pca_pesos_ind6=df_pca_pesos_ind6.set_index('Componentes Principales')
df_pca_pesos_ind6
plt.figure(figsize=(10,6), dpi= 200)
sns.heatmap(df_pca_pesos_ind6, cmap='RdYlGn', center=0, annot=True)
# fix for mpl bug that cuts off top/bottom of seaborn viz (see https://github.com/mwaskom/seaborn/issues/1773)
b, t = plt.ylim() # discover the values for bottom and top
b += 0.5 # Add 0.5 to the bottom
t -= 0.5 # Subtract 0.5 from the top
plt.ylim(b, t) # update the ylim(bottom, top) values
plt.title('Pesos de las Componentes Principales (6 indicadores base)')
plt.savefig('Pyplot_PCA_heatmap_ind6.png',dpi=600,bbox_inches="tight")
plt.show()
#calculo de la matriz de covarianza y sus correspondientes eigenvalores y eigenvectores
cov_mat = np.cov(x.T)
eigen_vals, eigen_vecs = np.linalg.eig(cov_mat)
# calculate of individual and cumulative sum of explained variances
tot = sum(eigen_vals)
var_exp = [(i / tot) for i in sorted(eigen_vals, reverse=True)]
cum_var_exp = np.cumsum(var_exp)
# plot explained variances
plt.figure(figsize=(10,6), dpi= 200)
plt.bar(range(1,7), var_exp, alpha=0.5,
align='center', label='varianza explicada individual')
plt.step(range(1,7), cum_var_exp, where='mid',
label='varianza explicada acumulada')
plt.ylabel('Razón de varianza explicada')
plt.xlabel('Índice Componentes Principales')
plt.legend(loc='best')
plt.title('Componentes Principales (6 indicadores base)')
plt.savefig('Pyplot_PCA_variance_ind6.png',dpi=600)
plt.show()
#concatenamos los resultados con los metadatos
df_pca_results_ind6 = pd.concat([metadatos[labels], df_pca_ind6], axis = 1)
df_pca_results_ind6.head()
#salvar resultados PCA
df_pca_results_ind6.to_csv(r'Resultados_Secc_PCA_ind6.csv', index = None)
Gráfica en el espacio CP1, CP2
#Scatter plot (seaborn) PC1 vs PC2
#(see https://www.machinelearningplus.com/plots/top-50-matplotlib-visualizations-the-master-plots-python)
plt.figure(figsize=(16, 10), dpi= 200, facecolor='w', edgecolor='k')
sns.scatterplot(x="CP1", y="CP2",
data=df_pca_results_ind6)
# Set x-axis label
plt.xlabel('CP1 (ICE principal)')
# Set y-axis label
plt.ylabel('CP2 (segundo ICE)')
plt.title('Proyección en CP1-CP2 (6 indicadores)')
plt.savefig('Pyplot_PCA_projection_ind6.png',dpi=600)
Gráfica en el espacio CP1, CP2, CP3
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.lines import Line2D
fig = pyplot.figure(figsize=(16, 10), dpi=200, facecolor='w', edgecolor='k')
ax = Axes3D(fig)
ax.scatter(df_pca_results_ind6['CP1'], df_pca_results_ind6['CP2'], df_pca_results_ind6['CP3'],s=20)
ax.set_xlim3d(0, 40)
ax.set_ylim3d(-20,5)
ax.set_zlim3d(-30,0)
ax.set_xlabel('CP1 (ICE principal)')
ax.set_ylabel('CP2 (segundo ICE)')
ax.set_zlabel('CP3 (tercer ICE)')
ax.view_init(elev, azim)
ax.set_title('Proyección en CP1-CP2-CP3 (6 indicadores)')
plt.savefig('Pyplot_PCA_3dprojection_ind6.png',dpi=600)
pyplot.show()
Gráfica 3d animada
# import plotly.express as px
# fig = px.scatter_3d(df_pca_results_ind6,
# x='CP1',
# y='CP2',
# z='CP3')
# fig.update_layout(scene = dict(
# xaxis_title='CP1 (ICE principal)',
# yaxis_title='CP2 (segundo ICE)',
# zaxis_title='CP3 (tercer ICE)'),
# legend_orientation="h")
# fig.show()
from sklearn.decomposition import PCA
#calculo de PCA (con las 6 componentes), y obtención de los valores CP para cada sección
pca_6cp_tf = PCA(n_components=6)
pca_ind6_tf = pca_6cp_tf.fit_transform(x_1)
#razones de varianza explicada por cada CP
print('Razón de varianza explicada por cada CP (n_components=6): %s'
% str(pca_6cp_tf.explained_variance_ratio_))
#dataframe con los valores de los 6 CP por sección
df_pca_ind6_tf = pd.DataFrame(data = pca_ind6_tf
, columns = ['CP1', 'CP2', 'CP3','CP4', 'CP5', 'CP6'])
df_pca_ind6_tf
#obtención de los pesos por cada variable
pca_pesos_ind6_tf = pca_6cp_tf.components_
print(pca_pesos_ind6_tf)
#transformación a un dataframe:
df_pca_pesos_ind6_tf = pd.DataFrame(pca_pesos_ind6_tf, columns=ind6_tf)
principal_components_pesos = pd.DataFrame(['CP1', 'CP2', 'CP3','CP4', 'CP5', 'CP6'])
df_pca_pesos_ind6_tf.insert(0, 'Componentes Principales', principal_components_pesos)
#se guarda el último dataframe en un csv
df_pca_pesos_ind6_tf.to_csv(r'Resultados_Secc_PCA_pesos_ind6_tf.csv', index = None)
df_pca_pesos_ind6_tf=df_pca_pesos_ind6_tf.set_index('Componentes Principales')
df_pca_pesos_ind6_tf
plt.figure(figsize=(10,6), dpi= 200)
sns.heatmap(df_pca_pesos_ind6_tf, cmap='RdYlGn', center=0, annot=True)
# fix for mpl bug that cuts off top/bottom of seaborn viz (see https://github.com/mwaskom/seaborn/issues/1773)
b, t = plt.ylim() # discover the values for bottom and top
b += 0.5 # Add 0.5 to the bottom
t -= 0.5 # Subtract 0.5 from the top
plt.ylim(b, t) # update the ylim(bottom, top) values
plt.title('Pesos de las Componentes Principales (6 indicadores base, con transformación log en LNE y Densidad_LNE)')
plt.savefig('Pyplot_PCA_heatmap_ind6_tf.png',dpi=600,bbox_inches="tight")
plt.show()
#calculo de la matriz de covarianza y sus correspondientes eigenvalores y eigenvectores
cov_mat = np.cov(x_1.T)
eigen_vals, eigen_vecs = np.linalg.eig(cov_mat)
# calculate of individual and cumulative sum of explained variances
tot = sum(eigen_vals)
var_exp = [(i / tot) for i in sorted(eigen_vals, reverse=True)]
cum_var_exp = np.cumsum(var_exp)
# plot explained variances
plt.figure(figsize=(10,6), dpi= 200)
plt.bar(range(1,7), var_exp, alpha=0.5,
align='center', label='varianza explicada individual')
plt.step(range(1,7), cum_var_exp, where='mid',
label='varianza explicada acumulada')
plt.ylabel('Razón de varianza explicada')
plt.xlabel('Índice Componentes Principales')
plt.legend(loc='best')
plt.title('Componentes Principales (6 indicadores base, con transformación log en LNE y Densidad_LNE)')
plt.savefig('Pyplot_PCA_variance_ind6_tf.png',dpi=600)
plt.show()
#concatenamos los resultados con los metadatos
df_pca_results_ind6_tf = pd.concat([metadatos[labels], df_pca_ind6_tf], axis = 1)
df_pca_results_ind6_tf.head()
#salvar resultados PCA
df_pca_results_ind6_tf.to_csv(r'Resultados_Secc_PCA_ind6_tf.csv', index = None)
Gráfica en el espacio CP1, CP2
#Scatter plot (seaborn) PC1 vs PC2
#(see https://www.machinelearningplus.com/plots/top-50-matplotlib-visualizations-the-master-plots-python)
plt.figure(figsize=(16, 10), dpi= 200, facecolor='w', edgecolor='k')
sns.scatterplot(x="CP1", y="CP2",
data=df_pca_results_ind6_tf)
# Set x-axis label
plt.xlabel('CP1 (ICE principal)')
# Set y-axis label
plt.ylabel('CP2 (segundo ICE)')
plt.title('Proyección en CP1-CP2 (6 indicadores, con transformación log en LNE y Densidad_LNE)')
plt.savefig('Pyplot_PCA_projection_ind6_tf.png',dpi=600)
Gráfica en el espacio CP1, CP2, CP3
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.lines import Line2D
fig = pyplot.figure(figsize=(16, 10), dpi=200, facecolor='w', edgecolor='k')
ax = Axes3D(fig)
ax.scatter(df_pca_results_ind6_tf['CP1'], df_pca_results_ind6_tf['CP2'], df_pca_results_ind6_tf['CP3'],s=20)
ax.set_xlim3d(0, 40)
ax.set_ylim3d(-20,5)
ax.set_zlim3d(-30,0)
ax.set_xlabel('CP1 (ICE principal)')
ax.set_ylabel('CP2 (segundo ICE)')
ax.set_zlabel('CP3 (tercer ICE)')
ax.view_init(elev, azim)
ax.set_title('Proyección en CP1-CP2-CP3 (6 indicadores, con transformación log en LNE y Densidad_LNE)')
plt.savefig('Pyplot_PCA_3dprojection_ind6_tf.png',dpi=600)
pyplot.show()
Gráfica 3d animada
# import plotly.express as px
# fig = px.scatter_3d(df_pca_results_ind6_tf,
# x='CP1',
# y='CP2',
# z='CP3')
# fig.update_layout(scene = dict(
# xaxis_title='CP1 (ICE principal)',
# yaxis_title='CP2 (segundo ICE)',
# zaxis_title='CP3 (tercer ICE)'),
# legend_orientation="h")
# fig.show()
from sklearn.decomposition import PCA
#calculo de PCA con 7 componentes, y obtención de los valores de CP para cada sección
pca_7cp = PCA(n_components=7)
pca_ind7 = pca_7cp.fit_transform(x_2)
#razones de varianza explicada por cada CP
print('Razón de varianza explicada por cada CP (n_components=7): %s'
% str(pca_7cp.explained_variance_ratio_))
#dataframe con los valores de los CP por sección
df_pca_ind7 = pd.DataFrame(data = pca_ind7
, columns = ['CP1', 'CP2', 'CP3','CP4', 'CP5', 'CP6','CP7'])
df_pca_ind7
#obtención de los pesos por cada variable
pca_pesos_ind7 = pca_7cp.components_
print(pca_pesos_ind7)
#transformación a un dataframe:
df_pca_pesos_ind7 = pd.DataFrame(pca_pesos_ind7, columns=ind7)
principal_components_pesos = pd.DataFrame(['CP1', 'CP2', 'CP3','CP4', 'CP5', 'CP6','CP7'])
df_pca_pesos_ind7.insert(0, 'Componentes Principales', principal_components_pesos)
#se guarda el último dataframe en un csv
df_pca_pesos_ind7.to_csv(r'Resultados_Secc_PCA_pesos_ind7.csv', index = None)
df_pca_pesos_ind7=df_pca_pesos_ind7.set_index('Componentes Principales')
df_pca_pesos_ind7
plt.figure(figsize=(10,6), dpi= 200)
sns.heatmap(df_pca_pesos_ind7, cmap='RdYlGn', center=0, annot=True)
# fix for mpl bug that cuts off top/bottom of seaborn viz (see https://github.com/mwaskom/seaborn/issues/1773)
b, t = plt.ylim() # discover the values for bottom and top
b += 0.5 # Add 0.5 to the bottom
t -= 0.5 # Subtract 0.5 from the top
plt.ylim(b, t) # update the ylim(bottom, top) values
plt.title('Pesos de las Componentes Principales (7 indicadores base)')
plt.savefig('Pyplot_PCA_heatmap_ind7.png',dpi=600,bbox_inches="tight")
plt.show()
#calculo de la matriz de covarianza y sus correspondientes eigenvalores y eigenvectores
cov_mat = np.cov(x_2.T)
eigen_vals, eigen_vecs = np.linalg.eig(cov_mat)
# calculate of individual and cumulative sum of explained variances
tot = sum(eigen_vals)
var_exp = [(i / tot) for i in sorted(eigen_vals, reverse=True)]
cum_var_exp = np.cumsum(var_exp)
# plot explained variances
plt.figure(figsize=(10,6), dpi= 200)
plt.bar(range(1,8), var_exp, alpha=0.5,
align='center', label='varianza explicada individual')
plt.step(range(1,8), cum_var_exp, where='mid',
label='varianza explicada acumulada')
plt.ylabel('Razón de varianza explicada')
plt.xlabel('Índice Componentes Principales')
plt.legend(loc='best')
plt.title('Componentes Principales (7 indicadores base)')
plt.savefig('Pyplot_PCA_variance_ind7.png',dpi=600)
plt.show()
#concatenamos los resultados con los metadatos
df_pca_results_ind7 = pd.concat([metadatos[labels], df_pca_ind7], axis = 1)
df_pca_results_ind7.head()
#salvar resultados PCA
df_pca_results_ind7.to_csv(r'Resultados_Secc_PCA_ind7.csv', index = None)
Gráfica en el espacio CP1, CP2
#Scatter plot (seaborn) PC1 vs PC2
plt.figure(figsize=(16, 10), dpi= 200, facecolor='w', edgecolor='k')
sns.scatterplot(x="CP1", y="CP2",
data=df_pca_results_ind7)
# Set x-axis label
plt.xlabel('CP1 (ICE principal)')
# Set y-axis label
plt.ylabel('CP2 (segundo ICE)')
plt.title('Proyección en CP1-CP2 (7 indicadores base)')
plt.savefig('Pyplot_PCA_projection_ind7.png',dpi=600)
Gráfica en el espacio CP1, CP2, CP3
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.lines import Line2D
fig = pyplot.figure(figsize=(16, 10), dpi=200, facecolor='w', edgecolor='k')
ax = Axes3D(fig)
ax.scatter(df_pca_results_ind7['CP1'], df_pca_results_ind7['CP2'], df_pca_results_ind7['CP3'],s=20)
ax.set_xlim3d(0, 40)
ax.set_ylim3d(-20,5)
ax.set_zlim3d(-30,0)
ax.set_xlabel('CP1 (ICE principal)')
ax.set_ylabel('CP2 (segundo ICE)')
ax.set_zlabel('CP3 (tercer ICE)')
ax.view_init(elev, azim)
ax.set_title('Proyección en CP1-CP2-CP3 (7 indicadores)')
plt.savefig('Pyplot_PCA_3dprojection_ind7.png',dpi=600)
pyplot.show()
Gráfica 3d animada
# import plotly.express as px
# fig = px.scatter_3d(df_pca_results_ind7,
# x='CP1',
# y='CP2',
# z='CP3')
# fig.update_layout(scene = dict(
# xaxis_title='CP1 (ICE principal)',
# yaxis_title='CP2 (segundo ICE)',
# zaxis_title='CP3 (tercer ICE)'),
# legend_orientation="h")
# fig.show()
from sklearn.decomposition import PCA
#calculo de PCA con 7 componentes, y obtención de los valores de CP para cada sección
pca_7cp_tf = PCA(n_components=7)
pca_ind7_tf = pca_7cp_tf.fit_transform(x_3)
#razones de varianza explicada por cada CP
print('Razón de varianza explicada por cada CP (n_components=7): %s'
% str(pca_7cp_tf.explained_variance_ratio_))
#dataframe con los valores de los CP por sección
df_pca_ind7_tf = pd.DataFrame(data = pca_ind7_tf
, columns = ['CP1', 'CP2', 'CP3','CP4', 'CP5', 'CP6','CP7'])
df_pca_ind7_tf
#obtención de los pesos por cada variable
pca_pesos_ind7_tf = pca_7cp_tf.components_
print(pca_pesos_ind7_tf)
#transformación a un dataframe:
df_pca_pesos_ind7_tf = pd.DataFrame(pca_pesos_ind7_tf, columns=ind7_tf)
principal_components_pesos = pd.DataFrame(['CP1', 'CP2', 'CP3','CP4', 'CP5', 'CP6','CP7'])
df_pca_pesos_ind7_tf.insert(0, 'Componentes Principales', principal_components_pesos)
#se guarda el último dataframe en un csv
df_pca_pesos_ind7_tf.to_csv(r'Resultados_Secc_PCA_pesos_ind7_tf.csv', index = None)
df_pca_pesos_ind7_tf=df_pca_pesos_ind7_tf.set_index('Componentes Principales')
df_pca_pesos_ind7_tf
plt.figure(figsize=(10,6), dpi= 200)
sns.heatmap(df_pca_pesos_ind7_tf, cmap='RdYlGn', center=0, annot=True)
# fix for mpl bug that cuts off top/bottom of seaborn viz (see https://github.com/mwaskom/seaborn/issues/1773)
b, t = plt.ylim() # discover the values for bottom and top
b += 0.5 # Add 0.5 to the bottom
t -= 0.5 # Subtract 0.5 from the top
plt.ylim(b, t) # update the ylim(bottom, top) values
plt.title('Pesos de las Componentes Principales (7 indicadores base, con transformación log en LNE y Densidad_LNE)')
plt.savefig('Pyplot_PCA_heatmap_ind7_tf.png',dpi=600,bbox_inches="tight")
plt.show()
#calculo de la matriz de covarianza y sus correspondientes eigenvalores y eigenvectores
cov_mat = np.cov(x_3.T)
eigen_vals, eigen_vecs = np.linalg.eig(cov_mat)
# calculate of individual and cumulative sum of explained variances
tot = sum(eigen_vals)
var_exp = [(i / tot) for i in sorted(eigen_vals, reverse=True)]
cum_var_exp = np.cumsum(var_exp)
# plot explained variances
plt.figure(figsize=(10,6), dpi= 200)
plt.bar(range(1,8), var_exp, alpha=0.5,
align='center', label='varianza explicada individual')
plt.step(range(1,8), cum_var_exp, where='mid',
label='varianza explicada acumulada')
plt.ylabel('Razón de varianza explicada')
plt.xlabel('Índice Componentes Principales')
plt.legend(loc='best')
plt.title('Componentes Principales (7 indicadores base, con transformación log en LNE y Densidad_LNE)')
plt.savefig('Pyplot_PCA_variance_ind7_tf.png',dpi=600)
plt.show()
#concatenamos los resultados con los metadatos
df_pca_results_ind7_tf = pd.concat([metadatos[labels], df_pca_ind7_tf], axis = 1)
df_pca_results_ind7_tf.head()
#salvar resultados PCA
df_pca_results_ind7_tf.to_csv(r'Resultados_Secc_PCA_ind7_tf.csv', index = None)
Gráfica en el espacio CP1, CP2
#Scatter plot (seaborn) PC1 vs PC2
plt.figure(figsize=(16, 10), dpi= 200, facecolor='w', edgecolor='k')
sns.scatterplot(x="CP1", y="CP2",
data=df_pca_results_ind7_tf)
# Set x-axis label
plt.xlabel('CP1 (ICE principal)')
# Set y-axis label
plt.ylabel('CP2 (segundo ICE)')
plt.title('Proyección en CP1-CP2 (7 indicadores base, con transformación log en LNE y Densidad_LNE)')
plt.savefig('Pyplot_PCA_projection_ind7_tf.png',dpi=600)
Gráfica en el espacio CP1, CP2, CP3
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.lines import Line2D
fig = pyplot.figure(figsize=(16, 10), dpi=200, facecolor='w', edgecolor='k')
ax = Axes3D(fig)
ax.scatter(df_pca_results_ind7_tf['CP1'], df_pca_results_ind7_tf['CP2'], df_pca_results_ind7_tf['CP3'],s=20)
ax.set_xlim3d(0, 40)
ax.set_ylim3d(-20,5)
ax.set_zlim3d(-30,0)
ax.set_xlabel('CP1 (ICE principal)')
ax.set_ylabel('CP2 (segundo ICE)')
ax.set_zlabel('CP3 (tercer ICE)')
ax.view_init(elev, azim)
ax.set_title('Proyección en CP1-CP2-CP3 (7 indicadores, con transformación log en LNE y Densidad_LNE)')
plt.savefig('Pyplot_PCA_3dprojection_ind7_tf.png',dpi=600)
pyplot.show()
Gráfica 3d animada
# import plotly.express as px
# fig = px.scatter_3d(df_pca_results_ind7_tf,
# x='CP1',
# y='CP2',
# z='CP3')
# fig.update_layout(scene = dict(
# xaxis_title='CP1 (ICE principal)',
# yaxis_title='CP2 (segundo ICE)',
# zaxis_title='CP3 (tercer ICE)'),
# legend_orientation="h")
# fig.show()